const consts = require('../consts.js');
const my = require('../lib/util.js');
const md5 = require('../lib/md5.js');
const order = require('order.js');
var __page = null;
const prepay = function(openid,order_id,order_type) {
  order.prepay({
    params: {
      "oid": openid,
      "order": order_id,
      "echo": order_type,
    },
    success: function (data) {
      console.log("wxpay:dopay:return="+JSON.stringify(data));
      var prepay_id = my.val(data);
      if (prepay_id == '' || prepay_id == 0) {
        console.log("wxpay:dopay:prepay_id error");
        my.error(__page, {
          msg: "错误的预支付ID",
          track: "PREPAY_ID=" + prepay_id,
        });
      } else {
        console.log("wxpay:dopay:prepay_id="+prepay_id);
        console.log("wxpay:dopay:order_id=" + order_id);
        my.L(order_id+"_prepay_id",prepay_id);
        dopay(prepay_id);
      }
    }
  });
};
const buildPaySign = function(data) {
  var arr = [];
  //小程序的APPID
  arr.push("appId=" + consts.PAY_APPID);
  arr.push("nonceStr=" + data.nonceStr);
  arr.push('package=' + data.package);
  arr.push('signType=' + data.signType);
  arr.push('timeStamp=' + data.timeStamp);
  //支付商户KEY
  arr.push('key=' + consts.PAY_KEY);
  var s = arr.join('&');
  console.log("wxpay:buildPaySign:data="+s);
  return md5.exec(s);
};
const dopay = function (prepay_id) {
  var data = {};
  data.timeStamp = Math.floor((new Date()).getTime() / 1000) + '';
  data.nonceStr = md5.exec(data.timeStamp);
  data.package = "prepay_id=" + prepay_id;
  data.signType = "MD5";
  data.paySign = buildPaySign(data);
  console.log("dopay data="+JSON.stringify(data));
  wx.requestPayment({
    'timeStamp': data.timeStamp,
    'nonceStr': data.nonceStr,
    'package': data.package,
    'signType': data.signType,
    'paySign': data.paySign,
    'success': __success,
    'fail': __fail
  });
};
var __success = function(){};
var __fail = function(){};
const call = function(json){
  __success = json.success;
  __fail = json.error;
  __page = json.page;
  console.log("wxpay:call:order_id="+json.order_id+",openid="+json.openid);
  prepay(json.openid,json.order_id,json.order_type);
};
module.exports = {
  call: call,
}
